#include <sys/stat.h>

#include "config.h"
#include "conf/serverconf.h"
#include "conf/mysqlconf.h"
#include "conf/redisconf.h"
#include "utils/fileutil.h"

Logger::ptr logger = LoggerMgr::GetInstance()->GetLogger("lvqiang");

Config<ServerConf>::ptr g_serverConf = ConfigMgr::GetInstance()->AddConfig("ServerConf",
                                            ServerConf(), "serverconf");
Config<MysqlConf>::ptr g_mysqlConf = ConfigMgr::GetInstance()->AddConfig("MysqlConf", 
                                            MysqlConf(), "mysqlconf");
Config<RedisConf>::ptr g_redisConf = ConfigMgr::GetInstance()->AddConfig("RedisConf",
                                            RedisConf(), "redisconf");

ConfigBase::ptr GetConfigBase(const std::string& name)
{
    auto it = ConfigMgr::GetInstance()->GetConfigMap().find(name);
    return it == ConfigMgr::GetInstance()->GetConfigMap().end() ? nullptr : it->second;
}

void ConfigManager::LoadFromYaml(const YAML::Node& root)
{
    if(root.IsMap())
    {
        for(auto it = root.begin(); it != root.end(); it++)
        {
            std::string key = it->first.as<std::string>();
            ConfigBase::ptr conf = GetConfigBase(key);
            std::stringstream ss;
            ss << it->second;
            conf->fromString(ss.str());
        }
    }
    else
    {
        //提示配置文件格式有问题
    }
}

void ConfigManager::LoadFromDir(const std::string& path)
{
    std::string absolute_path = "/home/lvqiang/vscodepro/zjh/conf";
    std::vector<std::string> files;
    FSUtil::ListAllFile(absolute_path, ".yml", files);

    for(auto i : files)
    {
        struct stat st;
        lstat(i.c_str(), &st);

        try
        {
            YAML::Node root = YAML::LoadFile(i);
            LoadFromYaml(root);
        }
        catch(const std::exception& e)
        {
            
        }
        
    }
}

void ConfigManager::Init()
{
    ConfigMgr::GetInstance()->LoadFromDir("");
}
